package cn.ddiancan.xddcloud.ddccore.config;

import cn.ddiancan.xddcloud.common.interceptor.FeignInterceptor;
import cn.ddiancan.xddcloud.common.security.JwtService;
import cn.ddiancan.xddcloud.ddccore.cache.XddCloudCacheClient;
import cn.ddiancan.xddcloud.ddccore.filter.ContextFilter;
import cn.ddiancan.xddcloud.ddccore.filter.LocalLoadHeaderFilter;
import com.github.pagehelper.PageInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

/**
 * 底座配置类
 *
 * @author Amos
 */
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableFeignClients(basePackages = "cn.ddiancan", defaultConfiguration = FeignInterceptor.class)
@ComponentScan(basePackages = "cn.ddiancan.xddcloud")
public class XddCloudConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(XddCloudConfiguration.class);

    @Bean
    public FilterRegistrationBean<ContextFilter> contextFilterBean(
        @Autowired(required = false) XddCloudCacheClient xddCloudCacheClient, JwtService jwtService) {
        FilterRegistrationBean<ContextFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new ContextFilter(xddCloudCacheClient, jwtService));
        filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean<LocalLoadHeaderFilter> loadHeaderFilterFilterBean() {
        FilterRegistrationBean<LocalLoadHeaderFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new LocalLoadHeaderFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        return filterRegistrationBean;
    }

    @Bean(value = "redisTemplate")
    @Primary
    @SuppressWarnings("unchecked")
    public XddCloudCacheClient xddCloudCacheClient(RedisConnectionFactory redisConnectionFactory) {
        XddCloudCacheClient xddCloudCacheClient = new XddCloudCacheClient();
        xddCloudCacheClient.setConnectionFactory(redisConnectionFactory);
        xddCloudCacheClient.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return xddCloudCacheClient;
    }

    @Bean
    public PageInterceptor pageInterceptor() {
        return new PageInterceptor();
    }
}
